﻿using DataModels.Dto;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using DataModels.Entities.Visitor;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Visitor
{
    public class VisitorService(SqlSugarClient db) : BaseService(db)
    {
        public ResponseModel GetVisitorByHousingBasicUUID(string HousingBasicUUID)
        {

            var result = db.Queryable<Visiter, Customer, HousingBasic, Building, Projects>((v, c, h, b, p) => new object[] {
                    JoinType.Left,v.UserUUID==c.UUID.ToString(),
                    JoinType.Left,v.HousingBasicUUID==h.UUID.ToString(),
                    JoinType.Left,h.BuildId==b.BuildId,
                    JoinType.Left,b.OrganId.ToString()==p.CommunityId,
                })
                .Where((v, c, h, b, p) => v.UserUUID == UserUUID.ToString())
                .Where((v, c, h, b, p) => v.HousingBasicUUID == HousingBasicUUID)
                .OrderBy((v, c, h, b, p) => v.CreateTime, OrderByType.Desc)
                  .Select((v, c, h, b, p) => new
                  {
                      v.UUID,
                      v.UserUUID,
                      v.HousingBasicUUID,
                      v.VisitName,
                      v.VisitNumber,
                      v.Describe,
                      v.DisabledTime,
                      v.IsVisit,
                      v.CreateTime,
                      p.ProjectName,
                      b.BuildName,
                      h.RoomNo,
                      c.Name,
                  }).ToList();
            return Success(result);

        }

        public  ResponseModel AddVisitor(Visiter visitRecord)
        {
            // 自动生成 UUID 和创建时间
            visitRecord.UUID = Guid.NewGuid().ToString();
            visitRecord.UserUUID = UserUUID.ToString();
            visitRecord.CreateTime = DateTime.Now;
            visitRecord.IsVisit = 0;
            var result =  db.Insertable(visitRecord).ExecuteCommand();
            return  result>0? Success(): Error("创建失败");
        }


        public ResponseModel EidtVisitor(string UUID,int IsVisit)
        {
            var entity = db.Queryable<Visiter>().Where(n=>n.UUID==UUID).First();
            entity.IsVisit = IsVisit;
            var result = db.Updateable(entity).ExecuteCommand();
            return result > 0 ? Success() : Error("访问失败");
        }
    }
}
